// controllers/orderController.js
const pool = require('../config/db');
const { sendResponse } = require('../utils/response');

// 创建订单
const createOrder = async (req, res) => {
  const { table_id, items } = req.body; // items: [{ type, dish_id, combo_id, quantity, remark, spicy_level }]
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    // 计算总金额
    let total_amount = 0;
    const orderItems = [];
    for (const item of items) {
      if (item.type === 0) { // 单点
        const [dishes] = await connection.execute('SELECT price FROM dishes WHERE id = ? AND status = 1', [item.dish_id]);
        if (dishes.length === 0) {
          await connection.rollback();
          return sendResponse(res, 404, '菜品未找到');
        }
        const dishPrice = dishes[0].price;
        total_amount += dishPrice * item.quantity;
        orderItems.push({
          type: 0,
          dish_id: item.dish_id,
          combo_id: null,
          quantity: item.quantity,
          price: dishPrice,
          spicy_level: item.spicy_level || null,
          remark: item.remark || null
        });
      } else if (item.type === 1) { // 套餐
        const [combos] = await connection.execute('SELECT price FROM combos WHERE id = ? AND status = 1', [item.combo_id]);
        if (combos.length === 0) {
          await connection.rollback();
          return sendResponse(res, 404, '套餐未找到');
        }
        const comboPrice = combos[0].price;
        total_amount += comboPrice * item.quantity;
        orderItems.push({
          type: 1,
          dish_id: null,
          combo_id: item.combo_id,
          quantity: item.quantity,
          price: comboPrice,
          spicy_level: null,
          remark: item.remark || null
        });
      } else {
        await connection.rollback();
        return sendResponse(res, 400, '无效的类型');
      }
    }

    // 插入订单
    const orderNo = 'ORD' + Date.now(); // 简单的订单号生成
    const [orderResult] = await connection.execute(
      'INSERT INTO orders (order_no, table_id, total_amount, status) VALUES (?, ?, ?, ?)',
      [orderNo, table_id, total_amount, 0] // 0-已下单
    );
    const orderId = orderResult.insertId;

    // 插入订单项
    for (const item of orderItems) {
      await connection.execute(
        'INSERT INTO order_items (order_id, dish_id, combo_id, type, quantity, price, spicy_level, remark) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
        [orderId, item.dish_id, item.combo_id, item.type, item.quantity, item.price, item.spicy_level, item.remark]
      );
    }

    await connection.commit();
    sendResponse(res, 201, '创建订单成功', { order_id: orderId, order_no: orderNo, total_amount });
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '创建订单失败', error.message);
  } finally {
    connection.release();
  }
};

// 获取订单列表（简单实现）
const getOrders = async (req, res) => {
  try {
    const [rows] = await pool.execute(`
      SELECT o.*, t.table_number 
      FROM orders o 
      LEFT JOIN tables t ON o.table_id = t.id 
      ORDER BY o.created_at DESC
    `);
    sendResponse(res, 200, '获取订单成功', rows);
  } catch (error) {
    sendResponse(res, 500, '获取订单失败', error.message);
  }
};

// 获取单个订单详情
const getOrderById = async (req, res) => {
  const { id } = req.params;
  try {
    const [orders] = await pool.execute(`
      SELECT o.*, t.table_number 
      FROM orders o 
      LEFT JOIN tables t ON o.table_id = t.id 
      WHERE o.id = ?
    `, [id]);
    if (orders.length === 0) {
      return sendResponse(res, 404, '订单未找到');
    }
    const order = orders[0];

    const [items] = await pool.execute(`
      SELECT oi.*, 
             d.name as dish_name, 
             d.image_url as dish_image_url,
             c.name as combo_name
      FROM order_items oi
      LEFT JOIN dishes d ON oi.dish_id = d.id
      LEFT JOIN combos c ON oi.combo_id = c.id
      WHERE oi.order_id = ?
    `, [id]);

    sendResponse(res, 200, '获取订单详情成功', { order, items });
  } catch (error) {
    sendResponse(res, 500, '获取订单详情失败', error.message);
  }
};

// 更新订单状态（简单实现）
const updateOrderStatus = async (req, res) => {
  const { id } = req.params;
  const { status } = req.body;
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    const [result] = await connection.execute('UPDATE orders SET status = ? WHERE id = ?', [status, id]);
    if (result.affectedRows === 0) {
      await connection.rollback();
      return sendResponse(res, 404, '订单未找到');
    }
    await connection.commit();
    sendResponse(res, 200, '更新订单状态成功');
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '更新订单状态失败', error.message);
  } finally {
    connection.release();
  }
};

module.exports = {
  createOrder,
  getOrders,
  getOrderById,
  updateOrderStatus
};